<?php
/**
 * Plugin Name: WP Message Box
 * Plugin URI: http://trancuongtruc.net
 * Description: WP Message Box plugin allows you to send message to other users
 * Version: 1.0
 * Author: Ryudo
 * Author URI: http://trancuongtruc.net
 * License: GPL2
 */

define("WP_MESSAGE_BOX_URL",  path_join(WP_PLUGIN_URL, basename(dirname(__FILE__))));
define("WP_MESSAGE_BOX_TABLE_NAME",$wpdb->prefix . "MessageBox");
function wpmb_installation() {
    global $wpdb;
   
    if ($wpdb->get_var("SHOW TABLES LIKE '" . WP_MESSAGE_BOX_TABLE_NAME."'") != WP_MESSAGE_BOX_TABLE_NAME) {
        $sql = "CREATE TABLE " . WP_MESSAGE_BOX_TABLE_NAME . " (
            id INTEGER(11) AUTO_INCREMENT,
            sent_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            title VARCHAR(255),
            message_content TEXT,
            from_user INTEGER(11) DEFAULT NULL,
            to_user INTEGER(11) DEFAULT NULL,
            is_read BOOL DEFAULT FALSE,
            delete_key INTEGER(11) DEFAULT NULL,
            PRIMARY KEY  (id) )
            CHARACTER SET UTF8";
        require_once(ABSPATH . "/wp-admin/includes/upgrade.php");
        dbDelta($sql);
        add_option("wpMessageBoxVersion", "1.0");
    } 
}

function wpmb_init() {
    global $wp_version;
    if (version_compare($wp_version, "3.1", ">=")) {
        wpmb_installation();
        wp_register_style("wpMessageBox.css", WP_MESSAGE_BOX_URL."/wpMessageBox.css");
        wp_enqueue_style("wpMessageBox.css");
    } else {

        function wpmb_init_warning() {
            echo _e("<div id='wpMessageBox_notice' class=\"error\"><p>Your wordpress version is not compatible with the plugin <strong>(Requires Wordpress version 3.1)</strong>. Please upgrade your wordpress</p></div>");
        }

        add_action("admin_notices", "wpmb_init_warning");
        return;
    }
}

function wpmb_get_messages_inbox() {
    global $wpdb;
    global $current_user;
    get_currentuserinfo();
    $sql = $wpdb->prepare("SELECT * FROM ".WP_MESSAGE_BOX_TABLE_NAME." WHERE to_user = %s",$current_user->ID);
    return $wpdb->get_results($sql,ARRAY_A);
    
}

function wpmb_get_messages_outbox() {
    global $wpdb;
    global $current_user;
    get_currentuserinfo();
    $sql = $wpdb->prepare("SELECT * FROM ".WP_MESSAGE_BOX_TABLE_NAME." WHERE from_user = %s",$current_user->ID);
    return $wpdb->get_results($sql,ARRAY_A);
    
}

function wpmb_get_username($userid) {
    global $wpdb;
    return $wpdb->get_row($wpdb->prepare("SELECT * FROM ".$wpdb->users." WHERE ID = %s",$userid))->user_login;
}

function wpmb_count_message($type) {
    global $wpdb;
    global $current_user;
    get_currentuserinfo();
    $total_record = 0;
    if($type == "inbox") {
        $total_record = $wpdb->get_var($wpdb->prepare("SELECT COUNT(*) FROM ".WP_MESSAGE_BOX_TABLE_NAME." WHERE to_user = %s",$current_user->ID));
    } else if($type == "outbox") {
        $total_record = $wpdb->get_var($wpdb->prepare("SELECT COUNT(*) FROM ".WP_MESSAGE_BOX_TABLE_NAME." WHERE from_user = %s",$current_user->ID));
    } else if($type == "unread") {
        $total_record = $wpdb->get_var($wpdb->prepare("SELECT COUNT(*) FROM ".WP_MESSAGE_BOX_TABLE_NAME." WHERE to_user = %s AND is_read = 0",$current_user->ID));
    }
    return $total_record;
}

function wpmb_table_generator($type) {
    if($type == "inbox") {
    ?>
    
         <table class="widefat">
            <thead>
                <tr>
                    <th>#</th>
                    <th>Read</th>
                    <th>From User</th>
                    <th>Sent Date</th>
                    <th>Title</th>
                    <th><input type="checkbox" name="msg_all" value="all" /></th>
                </tr>
            </thead>
            <tbody>
            <?php
            $messages = wpmb_get_messages_inbox();
            if (count($messages) > 0) {
                foreach ($messages as $message) {
            ?>
                    <tr>
                        <td><a href="index.php?page=manage-inbox&show_message=<?php echo $message['id']; ?>" ><?php echo $message['id']; ?></a></td>
                        <td><?php echo $message['is_read'] ? "Yes" : "No"; ?></td>
                        <td><?php echo wpmb_get_username($message['from_user']); ?></td>
                        <td><?php echo $message['sent_date']; ?></td>
                        <td><a href="index.php?page=manage-inbox&show_message=<?php echo $message['id']; ?>" ><?php echo $message['title']; ?></a></td>
                        <td><input type="checkbox" name="msg[]" value="<?php echo $message['id']; ?>"  class="wpmb_checkbox"/></td>
                    </tr>
                <?php } ?>
            <?php } else {
 ?>
                <tr>
                    <td colspan="6" style="text-align: center">You have no message right now.</td>
                </tr>
            <?php } ?>
        </tbody>
    </table>
    <?php } elseif($type == "outbox") { ?>
           <table class="widefat">
            <thead>
                <tr>
                    <th>#</th>
                    <th>Read</th>
                    <th>To User</th>
                    <th>Sent Date</th>
                    <th>Title</th>
                    <th><input type="checkbox" name="msg_all" value="all" /></th>
                </tr>
            </thead>
            <tbody>
            <?php
            $messages = wpmb_get_messages_outbox();
            if (count($messages) > 0) {
                foreach ($messages as $message) {
            ?>
                    <tr>
                        <td><a href="index.php?page=manage-inbox&show_message=<?php echo $message['id']; ?>" ><?php echo $message['id']; ?></a></td>
                        <td><?php echo $message['is_read'] ? "Yes" : "No"; ?></td>
                        <td><?php echo wpmb_get_username($message['to_user']); ?></td>
                        <td><?php echo $message['sent_date']; ?></td>
                        <td><a href="index.php?page=manage-inbox&show_message=<?php echo $message['id']; ?>" ><?php echo $message['title']; ?></a></td>
                        <td><input type="checkbox" name="msg[]" value="<?php echo $message['id']; ?>"  class="wpmb_checkbox"/></td>
                    </tr>
                <?php } ?>
            <?php } else {
 ?>
                <tr>
                    <td colspan="6" style="text-align: center">You have no message right now.</td>
                </tr>
            <?php } ?>
        </tbody>
    </table>
    <?php }
}

function wpmb_new_message($to_users,$content,$title = null) {
    global $wpdb;
    global $current_user;
    get_currentuserinfo();

    $list_users_not_found = array();
    $to_users = explode(";",$to_users);
    foreach($to_users as $user) {
        echo $user;
         $user_info = get_userdatabylogin($user);
        if($user_info == false) {
            $list_users_not_found = array_push($list_users_not_found,$user);
           // var_dump($list_users_not_found);
        }
    }
 
    if(empty($list_users_not_found)) {
        foreach($to_users as $user) {
            $result =  $wpdb->insert(WP_MESSAGE_BOX_TABLE_NAME,array("message_content"=>$content,
                                                    "from_user"=>$current_user->ID,
                                                    "to_user"=>$user_info->ID,
                                                    "title"=>$title),
                                                    array("%s","%s","%s","%s"));
        }
        return true;
    } else {
         return $list_users_not_found;
    }
   

}



function data_validation($input_name,$input_content,$patterns) {
    $patterns = explode("|", $patterns);
    $errors = array();
    foreach($patterns as $pattern) {
        if($pattern == "required") {
            if(!preg_match("/^[A-Za-z0-9]/",$input_content)) {
                array_push($errors,"You have entered invalid data on {$input_name} field ");
            }
        }
    }
    return $errors;
}

add_action("admin_init", "wpmb_init");
require_once(dirname(__FILE__)."/manage.php");
